/*
 * @Author: lin.zehong
 * @Date: 2019-07-22 10:05:52
 * @Last Modified by: lin.zehong
 * @Last Modified time: 2019-07-22 10:18:28
 * @Desc: 标签列表 和 我的标签 新增与编辑，根据 roleType 和 ROLE_TYPE_SUPER
 *        判断不同的角色。
 */
import React, { Component, Fragment } from "react";
import { Input, Button, TreeSelect, Spin, Form } from "antd";
import { connect } from "dva";
import { ROLE_TYPE_SUPER } from "../../labelManager/constants";
import styles from "./BaseInfo.less";
import SelectModal from "./SelectModal";
import UseObject from "./UseObject";

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};
const { TextArea } = Input;

const mapStateToProps = stores => ({
  user: stores.user,
  sceneData: stores.addScene,
  dataSourceData: stores.dataSource,
  orgList: stores.adddataSource,
  personDep: stores.personSelectModel
});

const mapDispatchToProps = dispatch => ({
  saveLabel(params) {
    return dispatch({
      type: "labelManager/saveLabel",
      payload: params
    });
  },
  modLabel(params) {
    return dispatch({
      type: "labelManager/modLabel",
      payload: params
    });
  },
  getOrgList() {
    return dispatch({
      type: "adddataSource/getOrgList",
      payload: {}
    });
  }
});

@connect(mapStateToProps, mapDispatchToProps)
@Form.create()
class AddLabelPage extends Component {
  state = ({
    useObject: [], // 使用对象
  })

  componentDidMount() {
    const { getOrgList } = this.props;
    getOrgList().then(() => {
      this.init();
    });
  }

  // 初始化设置归属部门
  init = () => {
    const { record } = this.props;
    if (record) {
      this.handleEditData();
    } else {
      this.handleAddData();
    }
  }

  // 初始化编辑数据处理
  handleEditData = () => {
    const { record } = this.props;
    const { ownerDept, octwnerDeptName, useObject, owner = [] } = (record && JSON.parse(record)) || {} ;
    const manager = owner.map(item => item.key);
    const managerName = owner.map(item => item.name);

    this.setState({
      ownerDept,
      octwnerDeptName,
      useObject,
      manager,
      managerName,
    });
  }

  // 初始化新增数据处理
  handleAddData = () => {
    const { form, user } = this.props;
    const { userInfo : { userId, userName, department, departmentName } = {} } = user; 
    form.setFieldsValue({ ownerDept: department});
    form.setFieldsValue({ owner: userName });

    this.setState({
      ownerDept: department,
      octwnerDeptName: departmentName,
      useObject: [],
      manager: [userId],
      managerName: [userName],
    });
  }

  // 处理使用对象
  handleUseObject = (desc, e) => {
    const useObject = this.handleManager(desc, e);
    this.setState({useObject});
  }

  // modal 确定
  save = () => {
    const { form, roleType } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if (roleType === ROLE_TYPE_SUPER) {
        this.validateUseObject(fieldsValue);
      } else {
        this.handleSubmit(fieldsValue);
      }
    });
  };

  // 表单校验使用对象
  validateUseObject = (fieldsValue) => {
    this.useObjectForm.props.form.validateFields((err) => {
      if (err) {
        this.useObjectForm.handleBorderVisible(true);
        return;
      }
      this.handleSubmit(fieldsValue);
    });
  };

  // 提交按钮
  handleSubmit = (fields) => {
    const { record, roleType, user } = this.props;
    const { userInfo : { department, departmentName, userId, userName } = {} } = user; // 我的标签，管理员、使用者、部门默认都是 user
    const { labelId } = (record && JSON.parse(record)) || {};
    const { ownerDept, octwnerDeptName, managerName, manager, useObject } = this.state;
    const owner = this.handleManager(managerName, manager);
    const { labelName, labelDescription } = fields;

    const params = {
      labelId,
      labelName,
      labelDescription,
      ownerDept: roleType === ROLE_TYPE_SUPER ? ownerDept : department,
      octwnerDeptName: roleType === ROLE_TYPE_SUPER ? octwnerDeptName : departmentName,
      owner: roleType === ROLE_TYPE_SUPER ? owner :  [{ key: userId, name: userName }],
      useObject: roleType === ROLE_TYPE_SUPER ? useObject : [{ key: userId, name: userName }],
      roleType
    };
    if (record) { // 编辑
      this.editLabel(params);
    } else {
      this.addLabel(params);
    }
  }

  // 新增标签
  addLabel = (params) => {
    const { saveLabel } = this.props;
    saveLabel(params);
  }

  // 编辑标签
  editLabel = (params) => {
    const { modLabel } = this.props;
    modLabel(params);
  }

  // 处理管理员数据
  handleManager = (descs, ids) => {
    const params = [];
    descs.forEach((item, index) => {
      params.push({name: item, key: ids[index] });
    });
    return params;
  }

  // 处理管理员编码和名称
  onDepart = (ownerDept, nameArr) => {
    this.setState({
      ownerDept,
      octwnerDeptName: nameArr.join()
    });
  };
  
  confirm = (e, desc) => {
    this.setState({ selectVisible: false, managerName: desc, manager: e });
    const { form } = this.props;
    form.setFieldsValue({ 'owner': desc && desc.length > 0 ? desc : "" });
  };

  closeModal = () => {
    this.setState({ selectVisible: false });
  };

  onCancel = () => {
    const { history, roleType } = this.props;
    if (roleType === ROLE_TYPE_SUPER) {
      history.push("/messageCenter/channelManager/labelManager");
    } else {
      history.push("/messageCenter/channelManager/myLabelManager");
    }
  }
  
  render() {
    const { user, sceneData, form, record, roleType } = this.props;
    const labelData = (record && JSON.parse(record)) || {} ;
    const { collapsed } = user;
    const { manager, managerName, selectVisible } = this.state;
    const { loading = false } = sceneData;
    const { orgList } = this.props;
    const { orgTree = [] } = orgList;
    
    return (
      <div>
        <div className={styles.root}>
          <SelectModal
            select={manager}
            selectdesc={managerName}
            visible={selectVisible}
            closeModal={this.closeModal}
            confirm={this.confirm}
            isMutiple={false}
            manager={true}
          />
          <Spin spinning={this.state.loadingEdit || loading}>
            <div className={styles.top}>
              <div className={styles.title}>基本信息</div>
              <div className={styles.basic}>
                <Form {...formItemLayout}>
                <FormItem label="标签名称">
                  {form.getFieldDecorator("labelName", {
                    rules: [
                      { required: true, message: "标签名称不能为空" },
                      { max: 25, message: "标签名称少于25个字" }
                    ],
                    initialValue: labelData.labelName
                  })(
                    <Input placeholder="请输入标签名称" />
                  )}
                  </FormItem>
                  
                  {
                    roleType === ROLE_TYPE_SUPER ?
                      <Fragment>
                        <FormItem label="管理员">
                          {form.getFieldDecorator("owner", {
                            rules: [
                              { required: true, message: "管理员不能为空" },
                            ],
                            initialValue: labelData.owner && labelData.owner.length
                              && labelData.owner[0].name
                          })(
                            <Input
                              placeholder="请选择管理员"
                              onClick={() => {
                                this.setState({ selectVisible: true });
                              }}
                            />
                          )}
                        </FormItem>

                        <FormItem label="归属部门">
                          {form.getFieldDecorator("ownerDept", {
                            rules: [
                              { required: true, message: "部门不能为空" },
                            ],
                            initialValue: labelData.ownerDept
                          })(
                            <TreeSelect
                              treeData={orgTree}
                              style={{ width: 460 }}
                              onChange={this.onDepart}
                              dropdownStyle={{ maxHeight: 350, overflow: "auto" }}
                              showCheckedStrategy="SHOW_PARENT"
                            />
                          )}
                        </FormItem>
                      </Fragment>
                      : null
                  }

                  <FormItem label="标签描述">
                    {form.getFieldDecorator("labelDescription", {
                      initialValue: labelData.labelDescription
                    })(
                      <TextArea
                        placeholder="请输入标签描述，100字以内"
                        maxLength={100}
                        rows={5}
                      />
                    )}
                  </FormItem>
                </Form>
              </div>
            </div>
          </Spin>
          {
            roleType === ROLE_TYPE_SUPER ? 
              <UseObject
                handleUseObject={this.handleUseObject}
                uObj={labelData.useObject}
                wrappedComponentRef={ref => {
                  this.useObjectForm = ref;
                }}
              />
              : null
          }
        </div>
        <div
          className={styles.footerWrap} 
          style={{width: collapsed ? "calc(100% - 66px)" : "calc(100% - 202px)"}}
        >
          <Button onClick={this.onCancel}>取消</Button>
          <Button
            type="primary"
            style={{ marginLeft: 8, marginRight: 16 }}
            onClick={this.save}
          >
            提交
          </Button>
        </div>
      </div>
    );
  }
}

export default AddLabelPage;
